﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace vs2017离线安装操作
{
    public partial class DownFile : Form
    {
        string fromPath = "";
        string downPath = "";

        public DownFile(string fromPath, string downPath)
        {
            InitializeComponent();
            this.fromPath = fromPath;
            this.downPath = downPath;
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="savefile"></param>
        /// <param name="downloadProgressChanged"></param>
        /// <param name="downloadFileCompleted"></param>
        private void DownloadFile(string url, string saveFile, Action<int> downloadProgressChanged, Action downloadFileCompleted)
        {
            WebClient client = new WebClient();
            client.Proxy = null;
            if (downloadProgressChanged != null)
            {
                client.DownloadProgressChanged += delegate (object sender, DownloadProgressChangedEventArgs e)
                {
                    this.Invoke(downloadProgressChanged, e.ProgressPercentage);
                };
            }
            if (downloadFileCompleted != null)
            {
                client.DownloadFileCompleted += delegate (object sender, AsyncCompletedEventArgs e)
                {
                    this.Invoke(downloadFileCompleted);
                };
            }
            client.DownloadFileAsync(new Uri(url), saveFile);
        }

        /// <summary>
        /// 下载完成
        /// </summary>
        private void DownloadFileCompleted()
        {
            //IsComlate = true;
            label1.Text = "下载完成";

            System.Threading.Thread.Sleep(1000);
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
        /// <summary>
        /// 显示进度
        /// </summary>
        /// <param name="val"></param>
        private void DownloadProgressChanged(int val)
        {
            progressBar1.Value = val;
            //Persent.Text = val.ToString() + "%";
            progressBar1.PerformStep();
        }

        private void DownFile_Shown(object sender, EventArgs e)
        {
            DownloadFile(this.fromPath, this.downPath, DownloadProgressChanged, DownloadFileCompleted);
        }
    }
}
